package com.huiquan.icd.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import com.huiquan.analysis.domain.User;
import com.huiquan.foundation.constant.BusinessContants;
import com.huiquan.foundation.constant.SubmitStatus;
import com.huiquan.framework.base.BaseService;
import com.huiquan.framework.base.ReturnData;
import com.huiquan.framework.constant.BaseContants;
import com.huiquan.framework.dao.EmailDao;
import com.huiquan.framework.utils.EMailUtil;
import com.huiquan.framework.utils.GetListUtil;
import com.huiquan.framework.utils.ReturnUtil;
import com.huiquan.icd.dao.IcdDiseaseDao;
import com.huiquan.icd.dao.IcdDiseaseIndexDao;
import com.huiquan.icd.domain.IcdDiseaseIndex;
import com.huiquan.management.constant.MigrateCode;
import com.huiquan.management.util.MigrateSwitch;

@Service
public class IcdDiseaseIndexService extends BaseService {

	@Autowired
	private IcdDiseaseIndexDao icdDiseaseIndexDao;
	@Autowired
	private IcdDiseaseDao icdDiseaseDao;
	@Autowired
	private MigrateSwitch migrateSwitch;

	public ModelAndView list(Integer start, String keyword, String exactSearchFlag, Integer status) {

		boolean exactFlag = exactSearchFlag != null && exactSearchFlag.equals("1");

		Map<String, Object> param = new HashMap<>();
		if (keyword != null && !keyword.isEmpty()) {
			param.put("keyword", exactFlag ? keyword : "%" + keyword + "%");
		}
		int totalSize = icdDiseaseIndexDao.retrieveSize(param);

		Map<String, Integer> pageNo = GetListUtil.getPageNoMap(totalSize, start, -1);

		int endPage = pageNo.get("endPage");
		start = pageNo.get("start");
		int startIndex = pageNo.get("startIndex");

		List<IcdDiseaseIndex> list = new ArrayList<>();

		if (startIndex < totalSize) {
			param.put("startIndex", startIndex);
			list = icdDiseaseIndexDao.retrieveList(param);
		}

		Map<String, String> showSearch = new LinkedHashMap<>();
		showSearch.put("keyword", "疾病名称");
		Map<String, String> searchMap = new HashMap<>();
		searchMap.put("keyword", keyword);
		Map<String, Object> map = GetListUtil.getReturnMap(status, totalSize, start, startIndex, endPage, list,
				searchMap);
		map.put("showSearch", showSearch);
		map.put("showSearchValue", searchMap);
		map.put("exactSearchFlag", exactSearchFlag);

		return new ModelAndView("icd/index", map);
	}

	public ReturnData checkFlag(String id, String flag, User user) {
		IcdDiseaseIndex icdDiseaseIndex = icdDiseaseIndexDao.retrieveObjectById(Long.parseLong(id));

		// 改变指标数据中的标志
		icdDiseaseIndex.setBlackFlag(Integer.parseInt(flag));
		icdDiseaseIndex.setCheckFlag(BaseContants.FLAG_YES);
		icdDiseaseIndex.setModifierId(user.getUserId());
		icdDiseaseIndex.setModifierName(user.getRealName());
		icdDiseaseIndexDao.update(icdDiseaseIndex);

		// 查询是否有未校验的指标，没有则更改是否校验状态为否
		icdDiseaseDao.updateCheckFlagByIndex(icdDiseaseIndex.getDiseaseName());

		return ReturnUtil.success();
	}

	public ModelAndView list(String dieaseName) {
		Map<String, Object> param = new HashMap<>();
		param.put("diseaseName", dieaseName);

		List<IcdDiseaseIndex> list = icdDiseaseIndexDao.retrieveList(param);

		Map<String, Object> map = new HashMap<>();
		map.put("list", list);
		map.put("name", dieaseName);

		return new ModelAndView("icd/index", map);
	}

	public ReturnData searchList(String diseaseName, String indexName, User user) {

		Map<String, Object> param = new HashMap<>();
		param.put("diseaseName", diseaseName);
		param.put("indexName", "%" + indexName + "%");
		List<IcdDiseaseIndex> list = icdDiseaseIndexDao.retrieveList(param);

		Map<String, Object> map = new HashMap<>();
		map.put("list", list);
		return ReturnUtil.success(map);
	}

	@Autowired
	private EMailUtil eMailUtil;
	@Autowired
	private EmailDao emailDao;

	public ReturnData submitServer() throws Exception {
		// 指标黑名单导出
		LOGGER.info("Icd disease generate inspection's blacklist begin!");

		// 该功能设置为运行中
		SubmitStatus.addSubmitRecords(SubmitStatus.TYPE_DISEASE_INSPECTION_BLACKLIST);

		Thread t = new Thread(new GenerateInspectionBlacklist());
		t.start();

		return ReturnUtil.success();
	}

	class GenerateInspectionBlacklist implements Runnable {

		@Override
		public void run() {
			try {

				// 导出“疾病-指标黑名单”
				migrateSwitch.migrateByCode(MigrateCode.DISEASE_INSPECTION_BLACKLIST);

				// 导出“疾病-指标白名单”
				migrateSwitch.migrateByCode(MigrateCode.DISEASE_INSPECTION_WHITELIST);

				// 发送邮件
				List<String> address = emailDao
						.retrieveAddressList(BusinessContants.SEND_EMAIL_GROUP_DISEASE_INSPECTION_CHECKED);
				if (!address.isEmpty()) {
					eMailUtil.sendBatchEmail("", "疾病指标黑名单已更新", address);
				}

			} catch (Exception e) {
				// 发送邮件
				List<String> address = emailDao.retrieveAddressList(BusinessContants.SEND_EMAIL_GROUP_STSTEM_ERROR);
				if (!address.isEmpty()) {
					try {
						eMailUtil.sendBatchEmail("", "疾病指标黑名单已更新", address);
					} catch (Exception e1) {
						e1.printStackTrace();
					}
				}

				e.printStackTrace();
			} finally {
				// 该功能从运行中去除
				SubmitStatus.removeSubmitRecords(SubmitStatus.TYPE_DISEASE_INSPECTION_BLACKLIST);

				LOGGER.info("Icd disease generate inspection's blacklist end!");
			}

		}
	}
}
